package linwen.wang.tdddemo.service;

import linwen.wang.tdddemo.vo.ProductInfo;
import linwen.wang.tdddemo.entity.ProductEntity;
import linwen.wang.tdddemo.entity.ProductTypeEntity;
import linwen.wang.tdddemo.repository.ProductRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;


    public List<ProductInfo> getProductsByIds(List<Long> ids) {
        List<ProductEntity> productEntities = productRepository.getProductsByIds(ids);
        List<Long> typeIds = new ArrayList<>();
        for (ProductEntity productEntity : productEntities) {
            typeIds.add(productEntity.getType());
        }
        List<ProductTypeEntity> typeEntities = productRepository.getProductTypes(typeIds);
        Map<Long, ProductTypeEntity> idToType = typeEntities.stream().collect(Collectors.toMap(ProductTypeEntity::getId,ProductTypeEntity-> ProductTypeEntity));
        List<ProductInfo> productInfoList = new ArrayList<>();
        for (ProductEntity productEntity : productEntities) {
            ProductInfo productInfo = new ProductInfo();
            BeanUtils.copyProperties(productEntity, productInfo);
            ProductTypeEntity productTypeEntity = idToType.get(productEntity.getId());
            productInfo.setTypeName(productTypeEntity.getName());
            productInfoList.add(productInfo);
        }
        return productInfoList;
    }
}
